<template>
  <!-- 页面标题区 -->
  <div class="page-header">
    <div class="page-title">
      <h1>题目管理</h1>
      <p class="text-muted">管理所有面试问题和评价标准</p>
    </div>
    <div class="page-actions">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>添加问题
      </el-button>
    </div>
  </div>

  <!-- 筛选区 -->
  <el-card class="filter-card">
    <el-row :gutter="20">
      <el-col :span="18">
        <el-form :inline="true" :model="queryParams" ref="queryFormRef">
          <el-form-item label="分类">
            <el-select v-model="queryParams.category" placeholder="全部分类" clearable style="width: 200px">
              <el-option
                v-for="item in categoryOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="难度">
            <el-select v-model="queryParams.difficulty" placeholder="全部难度" clearable style="width: 200px">
              <el-option
                v-for="item in difficultyOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="queryParams.status" placeholder="全部状态" clearable style="width: 200px">
              <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">
              筛选
            </el-button>
            <el-button @click="resetQuery">
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="6">
        <el-input
          v-model="queryParams.description"
          placeholder="搜索问题..."
          clearable
          @keyup.enter="handleQuery"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </el-col>
    </el-row>
  </el-card>

  <!-- 问题列表 -->
  <el-card>
    <template #header>
      <div class="card-header">
        <span>问题列表</span>
        <div class="card-actions">
          <el-button type="danger" :disabled="!selectedQuestions.length" @click="handleBatchDelete">
            批量删除
          </el-button>
        </div>
      </div>
    </template>

    <el-table
      v-loading="loading"
      :data="questionList"
      @selection-change="handleSelectionChange"
      style="width: 100%"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="题目内容" min-width="300">
        <template #default="{ row }">
          <div class="question-content">
            <div class="question-text">{{ row.description }}</div>
            <div class="question-tags">
              <el-tag
                v-for="tag in row.tagsArr"
                :key="tag"
                size="small"
                class="mx-1"
              >
                {{ tag }}
              </el-tag>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="分类" width="100" align="center">
        <template #default="{ row }">
          <el-tag type="primary" effect="plain">{{ row.title }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="难度" width="80" align="center">
        <template #default="{ row }">
          <el-tag :type="getDifficultyType(row.difficulty)" effect="plain">
            {{ row.difficultyLabel }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="120" prop="createdAt" align="center">
        <template #default="{ row }">
          {{ formatDate(row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column label="状态" width="80" align="center">
        <template #default="{ row }">
          <el-tag :type="row.status === 0 ? 'success' : 'info'" effect="plain">
            {{ row.status === 0 ? '启用' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right" align="center">
        <template #default="{ row }">
          <div class="operation-buttons">
            <el-link type="primary" :underline="false" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>编辑
            </el-link>
            <el-link type="danger" :underline="false" @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>删除
            </el-link>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </el-card>

  <!-- 添加/编辑问题对话框 -->
  <el-dialog
    v-model="dialogVisible"
    :title="dialogType === 'add' ? '添加问题' : '编辑问题'"
    width="70%"
  >
    <el-form
      ref="questionFormRef"
      :model="questionForm"
      :rules="rules"
      label-width="100px"
    >
          <el-form-item label="题目标题" prop="title">
            <el-input v-model="questionForm.title" placeholder="请输入题目标题" />
          </el-form-item>
          <el-form-item label="难度级别" prop="difficulty">
            <el-select v-model="questionForm.difficulty" placeholder="请选择难度">
              <el-option
                v-for="item in difficultyOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="题目分类" prop="category">
            <el-select v-model="questionForm.category" placeholder="请选择分类">
              <el-option
                v-for="item in categoryOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="标签">
            <el-tag
              v-for="tag in questionForm.tags.split(',')"
              :key="tag"
              closable
              @close="handleRemoveTag(tag)"
            >
              {{ tag }}
            </el-tag>
            <el-input
              v-if="inputVisible"
              ref="tagInputRef"
              v-model="inputValue"
              class="tag-input"
              size="small"
              @keyup.enter="handleInputConfirm"
              @blur="handleInputConfirm"
            />
            <el-button v-else class="button-new-tag" size="small" @click="showInput">
              + 新标签
            </el-button>
          </el-form-item>
          <el-form-item label="题目内容" prop="description">
            <el-input
              v-model="questionForm.description"
              type="textarea"
              :rows="4"
              placeholder="请输入题目内容"
            />
          </el-form-item>
          <el-form-item label="理想答案">
            <el-input
              v-model="questionForm.answer"
              type="textarea"
              :rows="4"
              placeholder="请输入理想答案"
            />
          </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="questionForm.status" placeholder="请选择状态">
          <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
          </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Edit, Delete } from '@element-plus/icons-vue'
import request from '@/utils/request'

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  category: '',
  difficulty: '',
  status: '',
  description: ''
})

// 查询表单引用
const queryFormRef = ref()

// 数据列表
const questionList = ref([])
const total = ref(0)
const loading = ref(false)
const selectedQuestions = ref([])

// 分类选项
const categoryOptions = ref([])

// 获取分类列表
const getCategoryList = async () => {
  try {
    const res = await request({
      url: '/api/questionCategory/list',
      method: 'get'
    })
    if (res.code === 200) {
      categoryOptions.value = res.data.map(item => ({
        value: item.name,
        label: item.name
      }))
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
    ElMessage.error('获取分类列表失败')
  }
}

// 难度选项
const difficultyOptions = [
  { value: '简单', label: '初级' },
  { value: '中等', label: '中级' },
  { value: '困难', label: '高级' }
]
const difficultyMap = {
  '简单': '初级',
  '中等': '中级',
  '困难': '高级'
}

// 状态选项
const statusOptions = [
  { value: 0, label: '启用' },
  { value: 1, label: '停用' }
]

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const activeTab = ref('basic')
const questionFormRef = ref()
const questionForm = reactive({
  id: undefined,
  title: '',
  description: '',
  difficulty: '',
  status: 1,
  category: '',
  problemsetId: undefined,
  tags: '', // 字符串，逗号分隔
  answer: '',
  background: '',
  createdAt: undefined,
  updatedAt: undefined
})

// 表单校验规则
const rules = {
  title: [{ required: true, message: '请输入题目标题', trigger: 'blur' }],
  description: [{ required: true, message: '请输入题目描述', trigger: 'blur' }],
  difficulty: [{ required: true, message: '请选择难度级别', trigger: 'change' }],
  problemsetId: [{ required: true, message: '请选择题目集', trigger: 'change' }],
  category: [{ required: true, message: '请选择题目分类', trigger: 'change' }]
}

// 标签输入相关
const inputVisible = ref(false)
const inputValue = ref('')
const tagInputRef = ref()

// 获取问题列表
const getList = async () => {
  loading.value = true
  try {
    let url = '/api/question/page'
    let params = {
      pageNum: queryParams.pageNum,
      pageSize: queryParams.pageSize
    }
    
    // 构建查询条件
    const conditions = []
    
    if (queryParams.category) {
      conditions.push({
        url: '/api/question/page/category',
        params: {
          pageNum: queryParams.pageNum,
          pageSize: queryParams.pageSize,
          name: queryParams.category
        }
      })
    }
    
    if (queryParams.difficulty) {
      conditions.push({
        url: '/api/question/page/difficulty',
        params: {
          pageNum: queryParams.pageNum,
          pageSize: queryParams.pageSize,
          difficulty: queryParams.difficulty
        }
      })
    }
    
    if (queryParams.status !== '') {
      conditions.push({
        url: `/api/question/page/status/${queryParams.status}`,
        params: {
          pageNum: queryParams.pageNum,
          pageSize: queryParams.pageSize
        }
      })
    }
    
    if (queryParams.description) {
      conditions.push({
        url: '/api/question/page/description',
        params: {
          pageNum: queryParams.pageNum,
          pageSize: queryParams.pageSize,
          description: queryParams.description
        }
      })
    }

    // 如果有多个条件，使用最后一个条件进行查询
    if (conditions.length > 0) {
      const lastCondition = conditions[conditions.length - 1]
      url = lastCondition.url
      params = lastCondition.params
    }

    const res = await request({
      url,
      method: 'post',
      params,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    })
    
    if (res.code === 200) {
      // 对结果进行二次过滤
      let filteredRecords = res.data.records
      
      if (queryParams.difficulty) {
        filteredRecords = filteredRecords.filter(q => q.difficulty === queryParams.difficulty)
      }
      if (queryParams.status !== '') {
        filteredRecords = filteredRecords.filter(q => q.status === queryParams.status)
      }
      if (queryParams.category) {
        filteredRecords = filteredRecords.filter(q => q.title === queryParams.category)
      }
      if (queryParams.description) {
        const keyword = queryParams.description.toLowerCase()
        filteredRecords = filteredRecords.filter(q => 
          q.description.toLowerCase().includes(keyword) || 
          q.title.toLowerCase().includes(keyword)
        )
      }

      questionList.value = filteredRecords.map(q => ({
        ...q,
        tagsArr: q.tags ? q.tags.split(',') : [],
        categoryName: categoryOptions.value.find(c => c.value === q.category)?.label || q.category,
        difficultyLabel: difficultyMap[q.difficulty] || q.difficulty
      }))
      total.value = filteredRecords.length
    }
  } catch (error) {
    console.error('获取问题列表失败:', error)
    ElMessage.error('获取问题列表失败')
  } finally {
    loading.value = false
  }
}

// 查询
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置查询
const resetQuery = () => {
  if (queryFormRef.value) {
    queryFormRef.value.resetFields()
  }
  queryParams.pageNum = 1
  getList()
}

// 表格选择项变化
const handleSelectionChange = (selection) => {
  selectedQuestions.value = selection
}

// 分页大小变化
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  getList()
}

// 页码变化
const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  getList()
}

// 获取难度标签类型
const getDifficultyType = (difficulty) => {
  const types = {
    '简单': 'success',
    '中等': 'warning',
    '困难': 'danger'
  }
  return types[difficulty] || 'info'
}

// 添加问题
const handleAdd = () => {
  dialogType.value = 'add'
  dialogVisible.value = true
  Object.assign(questionForm, {
    id: undefined,
    title: '',
    description: '',
    difficulty: '',
    status: 1,
    category: '',
    problemsetId: undefined,
    tags: '',
    answer: '',
    background: '',
    createdAt: undefined,
    updatedAt: undefined
  })
}

// 编辑问题
const handleEdit = (row) => {
  dialogType.value = 'edit'
  dialogVisible.value = true
  Object.assign(questionForm, row)
  // 设置分类为当前题目的标题（因为标题就是分类名称）
  questionForm.category = row.title
  // tags 字段转为字符串
  if (Array.isArray(row.tagsArr)) {
    questionForm.tags = row.tagsArr.join(',')
  }
}

// 查看问题
const handleView = (row) => {
  // TODO: 实现查看详情功能
  console.log('查看问题:', row)
}

// 删除单个问题
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确认要删除该问题吗？', '提示', {
      type: 'warning'
    })
    
    const res = await request({
      url: `/api/question/${row.id}`,
      method: 'delete'
    })
    
    if (res.code === 200) {
      ElMessage.success('删除成功')
      getList()
    }
  } catch (error) {
    console.error('删除失败:', error)
    ElMessage.error('删除失败')
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (!selectedQuestions.value.length) {
    ElMessage.warning('请选择要删除的问题')
    return
  }

  try {
    await ElMessageBox.confirm('确认要删除选中的问题吗？', '提示', {
      type: 'warning'
    })
    
    const ids = selectedQuestions.value.map(item => item.id)
    const res = await request({
      url: '/api/question/batch',
      method: 'delete',
      data: ids
    })
    
    if (res.code === 200) {
      ElMessage.success('删除成功')
      getList()
    }
  } catch (error) {
    console.error('批量删除失败:', error)
    ElMessage.error('批量删除失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!questionFormRef.value) return
  await questionFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 准备提交的数据
        const submitData = { ...questionForm }
        
        // 设置标题为分类名称
        submitData.title = submitData.category
        
        // tags 字段转为字符串
        if (Array.isArray(submitData.tags)) {
          submitData.tags = submitData.tags.join(',')
        }
        
        // 确保数值类型正确
        submitData.status = Number(submitData.status)
        
        if (dialogType.value === 'add') {
          const res = await request({
            url: '/api/question',
            method: 'post',
            data: submitData,
            headers: {
              'Content-Type': 'application/json'
            }
          })
          
          if (res.code === 200) {
            ElMessage.success('添加成功')
            dialogVisible.value = false
            getList()
          } else {
            throw new Error(res.message || '添加失败')
          }
        } else {
          const res = await request({
            url: '/api/question',
            method: 'put',
            data: submitData,
            headers: {
              'Content-Type': 'application/json'
            }
          })
          
          if (res.code === 200) {
            ElMessage.success('更新成功')
            dialogVisible.value = false
            getList()
          } else {
            throw new Error(res.message || '更新失败')
          }
        }
      } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error(error.message || '操作失败，请稍后重试')
      }
    }
  })
}

// 标签相关方法
const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    tagInputRef.value.focus()
  })
}
const handleInputConfirm = () => {
  if (inputValue.value) {
    // tags 字符串转数组，添加后再转回字符串
    let arr = questionForm.tags ? questionForm.tags.split(',') : []
    arr.push(inputValue.value)
    questionForm.tags = arr.join(',')
  }
  inputVisible.value = false
  inputValue.value = ''
}
const handleRemoveTag = (tag) => {
  let arr = questionForm.tags ? questionForm.tags.split(',') : []
  questionForm.tags = arr.filter(t => t !== tag).join(',')
}

onMounted(() => {
  getList()
  getCategoryList()
})
</script>

<style lang="scss" scoped>
.page-header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}
.filter-card {
  margin-bottom: 20px;
}
.question-content {
  .question-text {
    margin-bottom: 8px;
  }
  .question-tags {
    .el-tag {
      margin-right: 4px;
    }
  }
}
.interviewer-info {
  display: flex;
  align-items: center;
  gap: 8px;
  .interviewer-name {
    font-size: 14px;
  }
}
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
.tag-input {
  width: 100px;
  margin-left: 8px;
  vertical-align: bottom;
}
.button-new-tag {
  margin-left: 8px;
}
.interviewer-option {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px 0;
  .interviewer-info {
    .name {
      font-weight: 500;
    }
    .title {
      font-size: 12px;
      color: #666;
    }
  }
}
:deep(.el-dialog__body) {
  padding-top: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.card-actions {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  flex: 1;
}
.operation-buttons {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 12px;
}
.operation-buttons .el-link {
  display: flex;
  align-items: center;
  gap: 4px;
}
.operation-buttons .el-icon {
  font-size: 16px;
}
</style> 